import { Inject, Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { UserRoleType } from '@prisma/client';
import { LogService } from 'src/libs/log/log.service';
import { PrismaService } from 'src/libs/prisma/prisma.service';
import { RedisService } from 'src/libs/redis/redis.service';

@Injectable()
export class TaskService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;
  @Inject(RedisService)
  private readonly redisService: RedisService;
  @Inject(LogService)
  private readonly logService: LogService;

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async resetDailyPoints() {
    this.logService.info('✨ 更新降级用户角色中...');
    const roles = await this.prisma.userRole.findMany();
    const normalRoleId = roles.find((role) => role.role === UserRoleType.NORMAL)?.id;
    const vipRoleIds = roles.filter((role) => role.role !== UserRoleType.NORMAL)?.map((role) => role.id);
    await this.prisma.user.updateMany({
      where: {
        AND: [{ vipEndTime: { lt: new Date() } }, { roleId: { in: vipRoleIds } }],
      },
      data: {
        roleId: normalRoleId,
      },
    });
  }
}
